<?php

namespace app\logic\job;
use app\api\model\merchant\MerchantModel;
use think\facade\Log;
use think\queue\Job;
use ulit\thirdPayment\SafePay;
use app\api\model\order\Order;
class Pay
{

    /**
     * fire方法是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */

    // 定义任务的最大重试次数
    public function maxAttempts()
    {
        return 5; // 最大重试5次
    }


    public function fire(Job $job, $data)
    {

        if (empty($data)) {
            Log::write(sprintf('[%s][%s] 队列无消息', __CLASS__, __FUNCTION__));
            return false;
        }
        //获取队列提交信息
        $order_sn = $data['order_sn'];
        //如果有并发通知过来只处理一个
        $redislock = redisLocker();
        Log::record('队列参数'.json_encode($data), 'Pay');
        $resource = $redislock->lock('pay.' . $order_sn, 8000);   //单位毫秒
        Log::write(json_encode($resource),'pay');
        echo 'resource=>',json_encode($resource);
        //说明有订单在处理
        if (!$resource) {
            return $job->delete();
        }
        $delay = 3; // 延迟时间，单位秒
        $result =$this->payOrder($order_sn);

        $orderInfo = Order::where(['order_sn' => $order_sn])->field(['merchant_id', 'amount', 'commission','order_sn','third_ext_json','notify_state'])->find();
        $this->updateOrderStatus($orderInfo, $result);
        if ($result['orderStatus'] == 2) {
            Log::info('订单支付中，任务将被重新推送');
//
//            if ($job->attempts() > $this->maxAttempts()) {
//                $job->delete(); // 超过最大重试次数，删除任务
//                // 可以在这里记录任务失败日志
//                $this->failed($data);
//            } else {
//                $job->release($delay); // 释放任务，延迟一段时间后重新执行
//            }

            $job->release($delay);
            $redislock->unlock(['resource' => 'pay.' . $order_sn, 'token' => $resource['token']]);
            return true;
        }else{
            //通知区域
           $notify = new  Notify();
           if($orderInfo['notify_state']!=1){
              $state= $notify->run($orderInfo['third_ext_json'],$orderInfo['merchant_id'],$result);
              if($state){
                  Order::where(['order_sn' => $order_sn])->update(['notify_state'=>1]);
              }
           }

        }

        $redislock->unlock(['resource' => 'pay.' . $order_sn, 'token' => $resource['token']]);
        return $job->delete();

    }


    public function payOrder($order_sn)
    {
        try {

            $result=SafePay::getInstance()->query($order_sn);
            $arr=json_decode($result,true);
            Log::record('pay_callback'.json_encode($arr));

            if (isset($arr['result'])) {
                Log::info('支付回调结果'.json_encode($arr));
                return $arr['result'];
            }

            Log::error('支付回调结果无效');
            return ['orderStatus' => -1, 'message' => '支付回调结果无效'];
//            $arr=[];
//            // 定义数组
//            $numbers = [0, 1, 2, 4];
//
//// 使用 array_rand() 从数组中随机取出一个键
//            $randomKey = array_rand($numbers);
//
//            Log::write($randomKey);
//// 使用随机键从数组中获取对应的值
//            $randomValue = $numbers[$randomKey];
//            $arr['result']['orderStatus']=$randomValue;
//            $arr['result']['message']='test';
           // return $arr['result'];

         //

        } catch (\Exception $e) {
            $error_info = $e->getMessage();

            Log::record('pay_callback_error'.json_encode($error_info));

            return ['orderStatus' => -1, 'message' => $e->getMessage()];
        }
    }

    /**
     * 更新订单状态
     *
     * @param string $order_sn 订单号
     * @param array $result 支付结果
     */
    private function updateOrderStatus($orderInfo, $result)
    {

        if ($orderInfo) {
            if ($result['orderStatus'] == 1) {

                MerchantModel::where(['id' => $orderInfo['merchant_id']])
                    ->dec('money', $orderInfo['commission'])->update();
            }
            $update['status']=$result['orderStatus'];
            $update['pay_ext_json']=$result;
            !empty($result['remark']) &&  $update['pay_error_json']=['msg'=>$result['remark']];
            Order::where(['order_sn' => $orderInfo['order_sn']])->update($update);
        }
    }

    public function doJob($data)
    {
        echo '执行时间--->'.date('Y-m-d H:i:s')."\n";
        return false;
    }

    public function failed($data){

        // ...任务达到最大重试次数后，失败了
        Log::error('支付任务失败'.json_encode(['data' => $data], JSON_UNESCAPED_UNICODE));
    }


}
